import React, { forwardRef, useState, useImperativeHandle, ChangeEvent, useRef, useEffect } from 'react';
import { Button, Modal, Tooltip, Table, Space, Form, Pagination, Select, Tag, Image, Upload, DatePicker, UploadProps, DatePickerProps, TreeSelect, Switch, Empty } from 'antd';
import { WomanOutlined, ManOutlined, PlusOutlined, CloudUploadOutlined, QuestionCircleOutlined, InboxOutlined, FileOutlined } from '@ant-design/icons';
import systemApi from '../../../api/system';
import * as XLSX from "xlsx";
import { handleDownloadByName, handleDownloadByNameV2, isEmpty, toastShort } from '../../../utils';
import LoadingWapper from '../../../components/loading/LoadingWapper';
import { BJHSpeciesInfoType, SelectOption, SpeciesInfoType } from '../../../utils/types';
import axios from 'axios';
import { saasConfig } from '../../../config/theme-config';

interface Props {

}

const SpeciesNameFileModal = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        openModal: openModal
    }));

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);

    const delayTimer = useRef<any>(null);
    const delayTimer2 = useRef<any>(null);
    const [percent, setPercent] = useState<number>(0);
    const currentPercent = useRef<number>(0);
    const isActive = useRef<boolean>(false);
    const customSelectRef = useRef<any>(null);
    const tempDownloadUrl = useRef<string>(null);

    const docFileRef = useRef(null);

    const [currentFileName, setCurrentFileName] = useState("");

    const [loading, setLoading] = useState(false);
    const [speciesInfoList, setSpeciesInfoList] = useState<SpeciesInfoType[]>([]);

    useEffect(() => {
        return () => {
            delayTimer.current && clearTimeout(delayTimer.current);
            delayTimer2.current && clearTimeout(delayTimer2.current);
        }
    }, [])

    const openModal = () => {
        setIsModalOpen(true);
    }

    const handleConfirm = () => {
        setSubmitLoading(true);
        let formData = new FormData();
        formData.append("file", docFileRef.current);
        formData.append("speciesInfoList", JSON.stringify(speciesInfoList.filter(ele => ele.species_c && ele.canorical_me && ele.genus)));
        const instance = axios.create();
        instance.post(
            saasConfig.nodeJsApiBaseUrl + '/export-api/tools-service/fillSpeciesLatinName',
            formData,
            {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`,
                    "Content-Type": "multipart/form-data",
                },
            }
        )
            .then(res => {
                setSubmitLoading(false);
                toastShort('success', '拉丁名填充完毕！');
                console.log("res.data.url--->", res)
                handleDownloadByNameV2(res.data.data.url, currentFileName);
            })
            .catch(err => {
                setSubmitLoading(false);
            })
    }

    const handleCancel = () => {
        setIsModalOpen(false);
    }

    const uploadProps: UploadProps = {
        name: 'file',
        showUploadList: false,
        accept: '.xlsx',
        beforeUpload: (file) => {
            console.log("beforeUpload---->", file)
            let reader = new FileReader()
            reader.readAsBinaryString(file)//读取这个文件
            let _uploadParamsList = [];
            reader.onload = function (event) {
                try {
                    let result = event.target.result
                    let xlsxdata = XLSX.read(result, { type: 'binary' })//读取xlsx
                    // console.log("xlsxdata.Sheets--->", xlsxdata.Sheets)
                    const workSheetNameList: string[] = xlsxdata.SheetNames;
                    // console.log("workSheetNameList--->", workSheetNameList)
                    const spaciesSheet: string[][] = XLSX.utils.sheet_to_json(xlsxdata.Sheets[workSheetNameList[0]], { header: 1, defval: '', blankrows: true });
                    // console.log("spaciesSheet----->", spaciesSheet)
                    const tempSpeciesNameList = [];
                    spaciesSheet.forEach((row, rowIndex) => {
                        if (rowIndex > 0 && row[0]) {
                            tempSpeciesNameList.push(row[0])
                        }
                    })
                    setLoading(true);
                    let params = {
                        names: tempSpeciesNameList
                    };
                    systemApi.querySpeciesInfoMutiple(params)
                        .then(res => {
                            setLoading(false);
                            // console.log("querySpeciesInfoMutiple--->", res)
                            let tempspeciesInfoList: SpeciesInfoType[] = [];
                            tempSpeciesNameList.forEach(speciesName => {
                                const find: SpeciesInfoType = res.data.list.find(ele => {
                                    return ele.species_c === speciesName;
                                })
                                if (find) {
                                    if (isEmpty(find.genus)) {
                                        console.log("find--->", find)
                                        if (find.canorical_me) {
                                            find.genus = find.canorical_me.split(' ')[0];
                                            find.genus_c = find.genus_c || '未知科名';
                                            tempspeciesInfoList.push(find);
                                        }else {
                                            toastShort('error', find.species_c + "物种信息缺失")
                                        }
                                    }else {
                                        tempspeciesInfoList.push(find)
                                    }
                                } else {
                                    //@ts-ignore
                                    tempspeciesInfoList.push({
                                        species_c: speciesName
                                    })
                                }
                            })
                            setSpeciesInfoList(tempspeciesInfoList);
                        })
                        .catch(err => {
                            setLoading(false);
                        })
                } catch (e) {

                }
            }
            return false;
        },
        onChange(info) {
            return false;
        },
    };

    const uploadFileProps: UploadProps = {
        name: 'file',
        showUploadList: false,
        accept: '.docx',
        beforeUpload: (file) => {
            console.log("beforeUpload---->", file)
            docFileRef.current = file;
            setCurrentFileName(file.name);
        },
        onChange(info) {
            return false;
        },
    };


    const handleDownLoadTemplate = () => {
        handleDownloadByNameV2(
            'http://shpfile-data-1314977817.cos.ap-guangzhou.myqcloud.com/public/20230824512668dc1a-5e2b-43d9-ae46-72343666d02e67.xlsx',
            '物种名单上传模版(v2024-01-12.0.1)'
        )
    }

    return (
        <Modal
            title={"拉丁名填充"}
            open={isModalOpen}
            onOk={handleConfirm}
            onCancel={handleCancel}
            okButtonProps={{
                disabled: speciesInfoList.length == 0 || isEmpty(currentFileName)
            }}
            okText={'执行拉丁名填充'}
            cancelText={'取 消'}
            width={'800px'}
            maskClosable={false}
            confirmLoading={submitLoading}
            centered
        >
            <div className='flex-row word-editor-plugins-content benefit-evaluation-content'>

                <div className='flex-col' style={{ flex: 1, height: '60vh', border: '1px solid #ccc', borderRadius: 12, justifyContent: 'space-between' }}>
                    <div className="flex-row" style={{ width: '100%', height: 42, borderBottom: '1px solid #ccc' }}>
                        &nbsp;&nbsp;步骤一：物种清单
                    </div>
                    <div className='flex-row' style={{ width: '100%', flex: 1, overflowY: 'auto', justifyContent: 'center', alignItems: 'center' }}>
                        <LoadingWapper
                            loading={loading}
                        />
                        {
                            speciesInfoList.length ?
                                <div className='flex-row' style={{ width: '100%', flexWrap: 'wrap', padding: 18 }}>
                                    {
                                        speciesInfoList.map((speciesInfo, index) => {
                                            return (
                                                <div
                                                    key={index + ''}
                                                    className='species-name-tag'
                                                >
                                                    {
                                                        speciesInfo.canorical_me ?
                                                            <Tag
                                                                color="blue"
                                                                className='flex-row'
                                                                title={`${speciesInfo.species_c}(${speciesInfo.canorical_me})`}
                                                                style={{ marginBottom: 12 }}
                                                            >
                                                                {speciesInfo.species_c}
                                                                {
                                                                    <div
                                                                        style={{ fontStyle: 'italic', maxWidth: 72 }}
                                                                        className='single-line-text'
                                                                    >({speciesInfo.canorical_me})</div>
                                                                }
                                                            </Tag>
                                                            :
                                                            <Tag
                                                                color="red"
                                                                className='flex-row'
                                                            >
                                                                {speciesInfo.species_c}(查询失败)&nbsp;
                                                                <Tooltip title={'在本系统物种库中，未能查询到此物种信息'}>
                                                                    <QuestionCircleOutlined />
                                                                </Tooltip>
                                                            </Tag>
                                                    }
                                                </div>
                                            )
                                        })
                                    }
                                </div>
                                :
                                <div className='flex-col canorical-me-popover-empty' style={{ justifyContent: 'center', alignItems: 'center' }}>
                                    <Empty
                                        description={"暂无物种名单"}
                                    />
                                    <div
                                        className='link-text'
                                        onClick={handleDownLoadTemplate}
                                    >物种名单上传模版.xlsx</div>
                                </div>
                        }
                    </div>
                    <div className="flex-row" style={{ width: '100%', height: 42, borderTop: '1px solid #ccc', paddingRight: 12, justifyContent: 'flex-end' }}>
                        <Upload {...uploadProps}>
                            <Button
                                icon={<CloudUploadOutlined />}
                            >
                                上传物种名单
                            </Button>
                        </Upload>
                    </div>
                </div>
                <div style={{ width: 36 }}></div>
                <div className='flex-col' style={{ flex: 1, height: '60vh', border: '1px solid #ccc', borderRadius: 12 }}>
                    <div className="flex-row" style={{ width: '100%', height: 42, borderBottom: '1px solid #ccc' }}>
                        &nbsp;&nbsp;步骤二：待填充文档
                    </div>
                    <div className='flex-row' style={{ width: '100%', flex: 1, overflowY: 'auto', justifyContent: 'center', alignItems: 'center' }}>
                        {
                            currentFileName ?
                                <div className='flex-col' style={{ justifyContent: 'center'}}>
                                     <FileOutlined style={{fontSize: 50, marginBottom: 12}}/>
                                     <div style={{color: '#000'}}>{currentFileName}</div>
                                </div>
                                :
                                <div className='canorical-me-popover-empty'>
                                    <Empty
                                        description={"暂无待填充文档"}
                                    />
                                </div>
                        }
                    </div>
                    <div className="flex-row" style={{ width: '100%', height: 42, borderTop: '1px solid #ccc', paddingRight: 12, justifyContent: 'flex-end' }}>
                        <Upload {...uploadFileProps}>
                            <Button
                                icon={<CloudUploadOutlined />}
                            >
                                上传待填充文档(docx)
                            </Button>
                        </Upload>
                    </div>
                </div>
            </div>
        </Modal>
    )
}

export default forwardRef(SpeciesNameFileModal)